package com.github.rpc4j.producer.network;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent;

import com.github.rpc4j.common.ServiceRequest;
import com.github.rpc4j.common.ServiceResponse;
import com.github.rpc4j.producer.core.Rpc4jProducerContext;

public class NettyProducerHandler extends SimpleChannelUpstreamHandler {
	
	Rpc4jProducerContext context;
	
	public NettyProducerHandler(Rpc4jProducerContext context){
		this.context = context;
	}
	

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		super.exceptionCaught(ctx, e);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		ServiceRequest request = (ServiceRequest)e.getMessage();
		ServiceResponse result = context.getServicePool().callService(request);
		result.setRequestChannelId(request.getChannelId());
		ctx.getChannel().write(result);
	}

	@Override
	public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e)
			throws Exception {
		super.writeComplete(ctx, e);
	}
	
	
	
	

}
